package com.itheima.reggie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.entity.dto.OrderDetail;
import com.itheima.reggie.entity.dto.OrderDto;
import com.itheima.reggie.mappers.*;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.util.UUIDUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired(required = false)
    private OrderMapper orderMapper;

    @Autowired(required = false)
    private OrderDetailMapper orderDetailMapper;

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired(required = false)
    private AddressBookMapper addressBookMapper;

    /**
     * 作用： 下单  (本质：把购物车的数据转换为一个Orders 与多个OrderDetail)
     *
     * @param order 订单的信息（地址id，支付方式，备注）
     * @return
     */

    @Override
    public void submit(Orders order) {
        Long userId = order.getUserId();
        // A. 获得当前用户id, 查询当前用户的购物车数据
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.findAll(userId);

        // B. 根据当前登录用户id, 查询用户数据
        User user = userMapper.findById(userId);

        // C. 根据地址ID, 查询地址数据
        AddressBook addressBook = addressBookMapper.findById(order.getAddressBookId());
        //获得随机id
        long orderId = UUIDUtils.getUUIDInOrderId().longValue();

        BigDecimal totalAmount = new BigDecimal("0");

        // D. 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList = new ArrayList<>();

        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setId(UUIDUtils.getUUIDInOrderId().longValue());
            orderDetail.setName(shoppingCart.getName());
            orderDetail.setImage(shoppingCart.getImage());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(shoppingCart.getDishId());
            orderDetail.setSetmealId(shoppingCart.getSetmealId());
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());
            orderDetail.setNumber(shoppingCart.getNumber());
            orderDetail.setAmount(shoppingCart.getAmount());

            BigDecimal amount = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber() + ""));
            totalAmount = totalAmount.add(amount);
            orderDetailList.add(orderDetail);
        }

        // E. 组装订单数据, 批量保存订单数据
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(1);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setAmount(totalAmount);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setUserName(user.getName());
        order.setConsignee(addressBook.getConsignee());

        //插入订单
        orderMapper.save(order);
        //批量插入订单项
        orderDetailMapper.saveBatch(orderDetailList);

        // F. 删除当前用户的购物车列表数据
        shoppingCartMapper.clean(userId);
    }

    @Override
    public R<Page<OrderDto>> findByPage(Integer page, Integer pageSize, Long userId) {
        PageHelper.startPage(page, pageSize);
        List<Orders> ordersList = orderMapper.findByUserId(userId);

        PageInfo<Orders> pageInfo = new PageInfo<>(ordersList);

        List<OrderDto> orderDtoList = ordersList.stream().map(order -> {
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(order, orderDto);

            List<OrderDetail> orderDetailList = orderDetailMapper.findByOrderId(order.getNumber());

            orderDto.setOrderDetails(orderDetailList);
            return orderDto;
        }).collect(Collectors.toList());

        Page<OrderDto> orderDtoPage = new Page<>(orderDtoList, pageInfo.getTotal(), page, pageSize);

        return R.success(orderDtoPage);

    }

    @Override
    public R<Page<Orders>> findByNumberAndTime(Integer page, Integer pageSize, Long number, String beginTimeStr, String endTimeStr) {
        PageHelper.startPage(page, pageSize);

        //时间转换为LocalDateTime类型
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime beginTime = LocalDateTime.parse(beginTimeStr, dateTimeFormatter);
        LocalDateTime endTime = LocalDateTime.parse(endTimeStr, dateTimeFormatter);

        List<Orders> orderList = orderMapper.findByNumberAndTime(number, beginTime, endTime);


        PageInfo<Orders> pageInfo = new PageInfo<>(orderList);

        Page<Orders> orderPage = new Page<>(pageInfo.getList(), pageInfo.getTotal(), pageSize, page);

        return R.success(orderPage);
    }

}
